package com.bjpowernode.other.readwritelock;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.ReentrantReadWriteLock;

/**
 * 读写锁
 */
public class ReadWriteLock01 {
    public static void main(String[] args) {
        ReentrantReadWriteLock readWriteLock = new ReentrantReadWriteLock();

        //读任务
        Runnable r = () -> {
            try {
                //获取读锁
                readWriteLock.readLock().lock();
                TimeUnit.SECONDS.sleep(3);
                //模拟读取
                System.out.println(Thread.currentThread().getName() + ":" + System.currentTimeMillis());
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }finally {
                //释放锁
                readWriteLock.readLock().unlock();
            }
        };

        for (int i = 0; i < 5 ; i++) {
            new Thread(r).start();
        }
    }
}
